package cn.flc.web.Servlet;

import cn.flc.bean.User;
import cn.flc.mapper.UserMapper;
import cn.flc.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SqlSession sqlSession=null;
        try {
            //设置响应编码防止乱码
            resp.setContentType("text/html;charset=utf-8");
            //设置数据库接收用户乱码
            req.setCharacterEncoding("utf-8");
            //接收用户名,密码
            String username = req.getParameter("username");
       //     System.out.println(username);
            String password = req.getParameter("password");
            //调用mybatis查询用户
            //获取sqlsession
            SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtil.getSqlSessionFactory();
            //执行sql
            sqlSession = sqlSessionFactory.openSession();
            //获取USerMapper的代理对象
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            //调用方法
            User user = mapper.select(username, password);
            //准备打印
            PrintWriter writer = resp.getWriter();
            //判断是否成功
            if(user!=null){
                writer.write("登陆成功");
            }else{
                writer.write("登陆失败");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }finally {
            //关闭sqlsession
            sqlSession.close();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
